#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import shutil
import PropertiesReader

#执行渠道的定制操作
def carryChannelOper(sourceFile):
	defFileName = "ChannelCustomOper.py"
	
	if(True == os.path.exists(defFileName)):
		os.remove(defFileName)
	
	if(False == os.path.exists(sourceFile)):
		raise(sourceFile,"-源文件不存在，请检查")
	
	shutil.copy2(sourceFile, defFileName)
	
	cmdname = "python " + defFileName + " begin"
	os.system(cmdname)
	
#执行渠道恢复操作
def restoreChannelOper():
	defFileName = "ChannelCustomOper.py"
	
	cmdname = "python " + defFileName + " end"
	os.system(cmdname)
	
	if(True == os.path.exists(defFileName)):
		os.remove(defFileName)
	
#备份project.properties的源文件，再先后调用addRefChannel()和correctRefRelLib()）
def addRefLibWithBackup(gameOriAbsPath,gameCopyAbsPath,refLibAbsPath):
	workFileFullPath = gameCopyAbsPath+"/project.properties"
	backupFileFullPath = gameCopyAbsPath+"/project.properties_bak"

	if(False == os.path.exists(workFileFullPath)):
		raise(workFileFullPath,"-源文件不存在，请检查")

	if(True == os.path.exists(backupFileFullPath)):
		os.remove(backupFileFullPath)

	shutil.copy2(workFileFullPath, backupFileFullPath)
	addRefChannel(gameCopyAbsPath,"project.properties",refLibAbsPath)
	correctRefRelLib(gameOriAbsPath,gameCopyAbsPath,"project.properties")
	
#跟addRefLibWithBackup()配对使用，恢复原先的project.properties文件
def restoreProjectProperties(gameCopyAbsPath):
	workFileFullPath = gameCopyAbsPath+"/project.properties"
	backupFileFullPath = gameCopyAbsPath+"/project.properties_bak"

	if(True == os.path.exists(backupFileFullPath)):
		if(True == os.path.exists(workFileFullPath)):
			os.remove(workFileFullPath)		
		shutil.copy2(backupFileFullPath, workFileFullPath)
		os.remove(backupFileFullPath)
	
#1.将gameCopyAbsPath目录下的依赖库相对路径，都换成绝对路径（拼接过程中需要用到gameOriAbsPath）
#2.将gameCopyAbsPath目录下的project.properties中依赖库的绝对路径，更正为基于当前游戏工程gameCopyAbsPath的相对路径
#3.将修改后的project.properties文件保存在gameCopyAbsPath目录下
def correctRefRelLib(gameOriAbsPath,gameCopyAbsPath,filename):
	if( False == os.path.exists(gameOriAbsPath) ):
		raise Exception(gameOriAbsPath + "目录不存在，请检查!")
	if( False == os.path.exists(gameCopyAbsPath) ):
		raise Exception(gameCopyAbsPath + "目录不存在，请检查!")

	mFileName = gameCopyAbsPath + "/" + filename
	fileRead = open(mFileName, 'r')
	lines = fileRead.readlines()
	fileRead.close()
	
	fileWrite = open(mFileName, 'w')
	for line in lines: 
		if(line.startswith("android.library.reference")):
			reflibname = line.split("=")[0]
			reflibpath = line.split("=")[1]
			
			#拼接路劲，对两个绝对路径是不会生效的，所以不用担心二次拼接
			joinpath = os.path.join(gameOriAbsPath,reflibpath)
			abspath = os.path.abspath(joinpath)
			
			correctrelpath = getTrueRelPath(gameCopyAbsPath,abspath)
			
			fileWrite.write(reflibname + "=" + correctrelpath)
#			print(reflibname + "=" + abspath)
		else:
			fileWrite.write(line)
	fileWrite.close()
	
#将一个绝对路径refLibAbsPath，改成基于gamepropath的相对路径
def getTrueRelPath(gamepropath,refLibAbsPath):
	gamepropath = gamepropath.replace("\\","/")
	gameprolevel = gamepropath.count("/")
	
	refLibAbsPath = refLibAbsPath.replace("\\","/")
	desRelPathCutDiskSymtol = refLibAbsPath[3:]
	
	for index in range(0,gameprolevel):
		desRelPathCutDiskSymtol = "../" + desRelPathCutDiskSymtol
	
	return desRelPathCutDiskSymtol
	
#给project.properties文件增加一条依赖库的绝对路径
def addRefChannel(projectpath,filename,refPath):
	#获取依赖库号码最大的值
	p = PropertiesReader.PropertiesReader(projectpath + "/" + filename)
	properties = p.getProperties()
	
	maxrefnum = 0
	for ref in properties:
		if( True == ref.startswith("android.library.reference") ):
			num = int( ref.split(".",4)[3] )
			if(num>maxrefnum):
				maxrefnum = num
#	print("" + maxrefnum)
	
	refStr = "android.library.reference." + str(maxrefnum+1) + "=" + refPath
	f = open(projectpath+"/"+filename,'a')
	f.write("\n" + refStr + "\n")
	f.close()
	
# 递归拷贝目录
def dirCopyTree(src, dst):
	names = os.listdir(src)
	
	#目标文件夹不存在，则新建
	if not os.path.exists(dst):
		os.mkdir(dst)
		
	#遍历源文件夹中的文件与文件夹
	for name in names:
		if(name==".svn"):
			continue
			
		srcname = os.path.join(src, name)
		dstname = os.path.join(dst, name)
		try:
			#是文件夹则递归调用本拷贝函数，否则直接拷贝文件
			if os.path.isdir(srcname):
				dirCopyTree(srcname, dstname)
			elif ( not os.path.exists(dstname) or ((os.path.exists(dstname)) and (os.path.getsize(dstname) != os.path.getsize(srcname))) ):
#				print(dstname)
				shutil.copy2(srcname, dst)
		except:
			error.traceback();
			raise

# 备份目录
def dirBackup(srcDir,dstDir):
#	print("源文件夹" + srcDir)
#	print("目标文件夹" + dstDir)
#	print("本次拷贝文件：")
	dirCopyTree(srcDir, dstDir)

# 修改微信工程目录名
def changeWXEntryPackage(projectPath,originalPackage,newPackage):
	if(False == os.path.exists(projectPath)):
		raise(projectPath + "目录不存在，请检查！")
	
	#用新packageName创建一个目录
	newFullPath = projectPath + "/src/" + newPackage.replace(".","/") + "/wxapi"
	if(False == os.path.exists(newFullPath)):
		os.makedirs(newFullPath,True)

	#copy以前的WXEntryActivity到新目录下(需要修改第一行)
	originalFullPath = projectPath + "/src/" + originalPackage.replace(".","/") + "/wxapi"
	originalFileFullPath = originalFullPath+"/WXEntryActivity.java"
	newFileFullPath = newFullPath+"/WXEntryActivity.java"
	if(False == os.path.exists(originalFileFullPath)):
		raise(originalFileFullPath + "is not exist,changeWXEntryPackage pause")
	if(True == os.path.exists(originalFileFullPath)):
		if(originalFileFullPath == newFileFullPath):
			print("file path same , cancel copy")
			return
		if(True == os.path.exists(newFileFullPath)):
			shutil.rmtree(newFileFullPath,True)

		shutil.copy2(originalFileFullPath,newFileFullPath)
		fileRead = open(originalFileFullPath,'r')
		lines = fileRead.readlines()
		fileRead.close()

		fileWrite = open(newFileFullPath,'w')
		for line in lines: 
			if(line.startswith("package")):
				fileWrite.write("package " + newPackage + ".wxapi;\n")
			else:
				fileWrite.write(line)
		
		fileWrite.close()
	
# 恢复微信工程
def restpreWXEntryPackage(projectPath,originalPackage,newPackage):
	if(False == os.path.exists(projectPath)):
		raise(projectPath + "目录不存在，请检查！")
	
	originalFullPath = projectPath + "/src/" + originalPackage.replace(".","/") + "/wxapi"
	originalFileFullPath = originalFullPath+"/WXEntryActivity.java"
	newFullPath = projectPath + "/src/" + newPackage.replace(".","/") + "/wxapi"
	newFileFullPath = newFullPath+"/WXEntryActivity.java"
	if(originalFileFullPath == newFileFullPath):
		print("file path same , cancel restore")
		return
	
	#删除新建的WXEntryActivity对应的目录
	newPackPath = newPackage.replace(".","/")
	newFullPath = projectPath + "/src/" + newPackPath
	if(True == os.path.exists(newFullPath)):
#		print("begin to delete path ",newFullPath)
		shutil.rmtree(newFullPath,True)
	
	
if __name__=="__main__":
#	#
#	dirBackup("E:\SVN\CasualGames\popfarm_v6_four\proj.android","E:/gamecopy")
#	
#	#
#	refProPath = "E:/SVN/SGSDK/SGAna/SGBAIDU/SGBAIDU"
#	addRefChannel("E:/gamecopy","project.properties",refProPath)
#	
#	#
#	result = getTrueRelPath("E:\\gamecopy","E:\SVN\CasualGames\plugin\protocols\proj.android")
#	print(result)
#	
#	#
#	correctRefRelLib("E:\SVN\CasualGames\popfarm_v6_four\proj.android","E:/gamecopy","project.properties")
#	
#	#
#	carryChannelOper("E:/SVN/SGSDK/SGTools/SGAutoPack/autopack_v3_xiaobaoshi/channeloperation/meizu.py")
#	restoreChannelOper()
#	
#	#
#	addRefLibWithBackup("E:\SVN\CasualGames\popfarm_v6_four\proj.android","E:/gamecopy","E:/SVN/SGSDK/SGAna/SGBAIDU/SGBAIDU")
#	restoreProjectProperties("E:/SVN/SGSDK/SGAnd/SGAnd")
	
	#
	changeWXEntryPackage("E:/gamesource/plugin/plugins/weixin/proj.android","com.soulgame.bubbletwo","com.soulgame.bubbletwo.baidu")
#	restpreWXEntryPackage("E:/gamesource/plugin/plugins/weixin/proj.android","com.soulgame.bubbletwo.baidu")
#	changeWXEntryPackage("E:/SVN/SGSDK/SGTools/GameProject/weixin/proj.android","com.soulgame.hero","com.soulgame.hero.meizu")
#	restpreWXEntryPackage("E:/SVN/SGSDK/SGTools/GameProject/weixin/proj.android","com.soulgame.hero.baidu1")
	